//
//  GTGiftItemViewController.m
//  GiftTalk
//
//  Created by Wan on 16/3/25.
//  Copyright © 2016年 Wan. All rights reserved.
//  所搜结果 -> 礼物

#import "GTGiftItemViewController.h"
#import <AFNetworking.h>
#import "GTSearchGiftHeader.h"
#import "GTSearchGift.h"
#import <MJExtension.h>
#import "GTSearchGiftCell.h"
#import "GTGiftDetailViewController.h"

@interface GTGiftItemViewController ()
/** 请求管理器 */
@property (strong, nonatomic) AFHTTPSessionManager *manager;
/** 下一页请求 url */
@property (strong, nonatomic) NSString *nextPageUrl;
/** 礼物数组 */
@property (strong, nonatomic) NSMutableArray *searchGifts;
@end

@implementation GTGiftItemViewController

#pragma mark - 懒加载
- (NSString *)firstPageURLString {
    if (_firstPageURLString== nil) {
        _firstPageURLString = @"http://api.liwushuo.com/v2/items?gender=1&generation=1&limit=20&offset=0";
    }
    return _firstPageURLString;
}

- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.session.configuration.timeoutIntervalForRequest = GTTimeoutIntervalForRequest;
    }
    return _manager;
}

- (NSString *)nextPageUrl
{
    if (!_nextPageUrl) {
        _nextPageUrl = @"http://api.liwushuo.com/v2/items?gender=1&generation=1&limit=20&offset=0";
    }
    return _nextPageUrl;
}

- (NSMutableArray *)searchGifts
{
    if (!_searchGifts) {
        _searchGifts = [NSMutableArray array];
    }
    return _searchGifts;
}

#pragma mark - 初始化
- (instancetype)init
{
    CGFloat width = (GTScreenW - 3 * GTSearchGiftCellMargin) * 0.5;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(width, GTCollectionItemHeight);
    // item 之间的最小间距
    flowLayout.minimumInteritemSpacing = GTSearchGiftCellMargin;
    flowLayout.sectionInset = GTTableViewCellUIEdgeInsets;
    
    return [super initWithCollectionViewLayout:flowLayout];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"礼物详情";
    self.collectionView.backgroundColor = GTBackgroundColor;
    
    self.collectionView.mj_header = [GTSearchGiftHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self.collectionView.mj_header beginRefreshing];
}


#pragma mark - 加载数据
- (void)loadNewData
{
    [self.manager GET:self.firstPageURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        GTLog(@"%@",responseObject);
        
        self.nextPageUrl = responseObject[@"data"][@"paging"][@"next_url"];
        NSArray *array = responseObject[@"data"][@"items"];
        if ([[array firstObject][@"type"] isEqualToString:@"item"]) {
            for (NSDictionary *dict in array) {
                GTSearchGift *gift = [GTSearchGift mj_objectWithKeyValues:dict[@"data"]];
                [self.searchGifts addObject:gift];
            }
        }else {
            [self.searchGifts addObjectsFromArray:[GTSearchGift mj_objectArrayWithKeyValuesArray:array]];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
//        NSArray *array = responseObject[@"data"][@"items"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
        
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData
{
    [self.manager GET:self.nextPageUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.nextPageUrl = responseObject[@"data"][@"paging"][@"next_url"];
        NSArray *array = responseObject[@"data"][@"items"];
        if ([[array firstObject][@"type"] isEqualToString:@"item"]) {
            for (NSDictionary *dict in array) {
                GTSearchGift *gift = [GTSearchGift mj_objectWithKeyValues:dict[@"data"]];
                [self.searchGifts addObject:gift];
            }
        }else {
            [self.searchGifts addObjectsFromArray:[GTSearchGift mj_objectArrayWithKeyValuesArray:array]];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
        
        [self.collectionView.mj_footer endRefreshing];
    }];
}


- (void)dealloc
{
    [self.manager invalidateSessionCancelingTasks:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.searchGifts.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GTSearchGiftCell *cell = [GTSearchGiftCell cellWithCollectionView:collectionView forIndexPath:indexPath];
    GTSearchGift *gift = self.searchGifts[indexPath.item];
    cell.gift = gift;
    return cell;
}

#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GTGiftDetailViewController *giftDetailVc = [[GTGiftDetailViewController alloc] init];
    GTSearchGift *gift = self.searchGifts[indexPath.item];
    giftDetailVc.giftId = gift.ID;
    [self.navigationController pushViewController:giftDetailVc animated:YES];
}


@end
